/**
 * @file 01_select.c
 * @author your name (you@domain.com)
 * @brief illustrate wait stdin data
 * @version 0.1
 * @date 2022-10-13
 * 
 * @copyright Copyright (c) 2022
 * 
 */

#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>
#include <assert.h>

int main(void)
{
    int fd = STDIN_FILENO;
    fd_set readset;

    while (1)
    {
        FD_ZERO(&readset);
        FD_SET(fd, &readset);
        struct  timeval tv = {5, 0};
        /*
        On  exit,  each  of  the  file  descriptor  sets is modified in place to indicate which file descriptors actually changed status.
       (Thus, if using select() within a loop, the sets must be reinitialized before each call.)
        */
        int retval = select(fd + 1, &readset, NULL, NULL, &tv);

        if (-1 == retval)
        {
            perror("select");
            break;
        }
        else if (0 == retval)
        {
            printf("time out\n");
        }
        else
        {
            assert(1 == retval);
            for (int i = 0; i < retval; i++)
            {
                if (FD_ISSET(fd, &readset))
                {
                    char buf[1024] = {0};
                    read(fd, buf, 1024);
                    printf("read: %s\n", buf);
                }
            }
        }
    }
}